package com.zlyx.easy.core.utils;

import com.zlyx.easy.core.utils.ByteUtils;
import com.zlyx.easy.core.utils.HexUtils;

/**
 * 
 * @Auth 赵光
 * @Desc 描述 Byte操作工具
 * @Date 2019年4月8日
 */
public class ByteUtils {

	/**
	 * 十六进制转字符串
	 * 
	 * @param hexStr
	 * @return
	 */
	public static String hexToString(String hexStr) {

		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;
		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}

	/**
	 * 十六进制转byte数组
	 * 
	 * @param hex
	 * @return
	 */
	public static byte[] hexStringToByte(String hex) {
		String str = "0123456789ABCDEF";
		char[] hexs = hex.toCharArray();
		byte[] bytes = new byte[hex.length() / 2];
		int n;
		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return bytes;
	}

	/**
	 * byte数组转十六进制
	 * 
	 * @param src
	 * @return
	 */
	public static String bytesToHexString(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)
				sb.append(0);
			sb.append(sTemp.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 字符转byte
	 * 
	 * @param c
	 * @return
	 */
	public static byte toByte(char c) {
		byte b = (byte) "0123456789abcdef".indexOf(c);
		return b;
	}

	/**
	 * byte转16进制
	 * 
	 * @param b
	 * @return
	 */
	public static String byteToHex(byte b) {
		byte[] lm = { (b) };
		return ByteUtils.bytesToHexString(lm);
	}

	/**
	 * int转16进制
	 * 
	 * @param b
	 * @return
	 */
	public static String byteToHex(int i) {
		return HexUtils.toHex(String.valueOf(i));
	}

}
